package com.dyh.quickdemozwei.omsutil;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public interface DhUtil {
    String [] dhArr = {
            "https://databasehub.leqee.com/api/QuickQueryController/syncExecute",
            "https://databasehub.guanyc.cn/api/QuickQueryController/syncExecute"
    };

    static JSONObject gentBodyJo(Integer id, String token, String sql){
        JSONObject jo = new JSONObject();
        jo.put("database_id",id);
        jo.put("token",token);
        jo.put("sql",sql);
        return jo;
    }

    static JSONObject gentBodyJo(Integer id,String token){
        JSONObject jo = new JSONObject();
        jo.put("database_id",id);
        jo.put("token",token);
        return jo;
    }

    static List<JSONObject> callAutoPage(JSONObject reqJo, int dhIdx){

        int offset = 30;
        String originSql = reqJo.getString("sql");
        List<JSONObject> allJa = new ArrayList<>();
        for (;;){
            HttpResponse resp = HttpRequest.post(dhArr[dhIdx])
                    .body(JSON.toJSONString(reqJo))
                    .timeout(50000)
                    .setReadTimeout(50000)
                    .header("Content-Type", "application/json").execute();

            JSONObject respJo = JSON.parseObject(resp.body());

            List<JSONObject> ja = JSON.parseArray(respJo.getJSONObject("data").getString("data"),JSONObject.class);

            allJa.addAll(ja);


            if (ja.size()<30)
                break;

            reqJo.put("sql",String.format("%s limit %s,30",originSql,offset));
            offset+=30;
        }

        return allJa;

    }

    static void show(List<JSONObject> ja){
        for (JSONObject jsonObject : ja) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                sb.append(String.format("%s %s",entry.getKey(),String.valueOf(entry.getValue())));
            }
            System.out.println(sb);
        }
    }
}
